package com.gufe.service.admin.impl.veteran;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gufe.entity.VMQueryParam;
import com.gufe.entity.VeteranMember;
import com.gufe.exception.EmptyFieldException;
import com.gufe.mapper.admin.veteran.VeteranMemberMapper;
import com.gufe.result.PageResult;
import com.gufe.service.admin.veteran.VeteranMemberService;
import com.gufe.utils.ImportExcelUtil;
import com.gufe.vo.VeteranMemberVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class VeteranMemberServiceImpl implements VeteranMemberService {

    @Autowired
    private VeteranMemberMapper veteranMemberMapper;

    // 分页条件查询退伍人员信息
    public PageResult getMemberInfo(VMQueryParam vmQueryParam) {
        // 使用PageHelper进行分页，获取分页参数
        PageHelper.startPage(vmQueryParam.getPage(), vmQueryParam.getPageSize());

        // 执行分页查询，此时SQL会自动添加分页限制
        List<VeteranMember> veteranMembers = veteranMemberMapper.getMemberInfo(vmQueryParam);

        // 将查询结果强制转换为Page对象以获取分页信息
        Page<VeteranMember> page = (Page<VeteranMember>) veteranMembers;
        // 转换为VO列表
        List<VeteranMemberVO> veteranMemberVOs = new ArrayList<>();
        for (VeteranMember member : veteranMembers) {
            VeteranMemberVO vo = new VeteranMemberVO();
            BeanUtils.copyProperties(member, vo);
            // 转换状态字段
            vo.setGender(member.getGender() == 1 ? "男" : "女");
            vo.setIsServing(member.getIsServing() == 1 ? "是" : "否");
            // vo.setHasMeritorious(member.getHasMeritorious() == 1 ? "是" : "否");
            veteranMemberVOs.add(vo);
        }
        // 返回分页结果，包含总记录数和处理后的VO列表
        return new PageResult(page.getTotal(), veteranMemberVOs);
    }


    public String importExcelVeteran(MultipartFile file){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<VeteranMember> veteranMemberList = new ArrayList<>();

        //验证文件类型
        if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls")&&!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")){
            return "文件类型有误！请上传Excle文件";
        }
        //获取数据
        List<List<Object>> olist = null;
        try {
            olist = ImportExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //封装数据
        for (int i = 0; i < olist.size(); i++) {
            List<Object> list = olist.get(i);
            // 跳过标题行
            if (list.get(0) == "" || ("序号").equals(list.get(0))) {
                continue;
            }
            VeteranMember veteranMember = new VeteranMember();
            //根据下标获取每一行的每一条数据
            if (String.valueOf(list.get(1))==null||String.valueOf(list.get(1)).isEmpty()) {
                throw new EmptyFieldException("姓名不能为空!!!");
            }
            veteranMember.setName(String.valueOf(list.get(1)));


            if (String.valueOf(list.get(2))==null||String.valueOf(list.get(2)).equals("")) {
                return "性别不能为空";
            }
            String genderStr = String.valueOf(list.get(2)).trim();
            int gender = "男".equals(genderStr) ? 1 : ("女".equals(genderStr) ? 2 : 0);
            veteranMember.setGender(gender);


            if (String.valueOf(list.get(3))==null||String.valueOf(list.get(3)).equals("")) {
                return "身份证号不能为空";
            }
            veteranMember.setIdCard(String.valueOf(list.get(3)));

            String nationality = String.valueOf(list.get(4)).trim(); // 修改索引为4
            veteranMember.setNationality(nationality.isEmpty() ? null : nationality);

            // 政治面貌
            String politicalAffiliation = String.valueOf(list.get(5)).trim(); // 修改索引为5
            veteranMember.setPoliticalAffiliation(politicalAffiliation.isEmpty() ? null : politicalAffiliation);

            // 学历
            String educationLevel = String.valueOf(list.get(6)).trim();
            veteranMember.setEducationLevel(educationLevel.isEmpty() ? null : educationLevel);

            // 学籍状态
            String academicStatus = String.valueOf(list.get(7)).trim();
            veteranMember.setAcademicStatus(academicStatus.isEmpty() ? null : academicStatus);

            // 学院
            String college = String.valueOf(list.get(8)).trim();
            veteranMember.setCollege(college.isEmpty() ? null : college);

            // 专业
            String major = String.valueOf(list.get(9)).trim();
            veteranMember.setMajor(major.isEmpty() ? null : major);

            // 学号
            String studentId = String.valueOf(list.get(10)).trim();
            veteranMember.setStudentId(studentId.isEmpty() ? null : studentId);

            // 家庭地址
            String familyAddress = String.valueOf(list.get(11)).trim();
            veteranMember.setFamilyAddress(familyAddress.isEmpty() ? null : familyAddress);

            // 联系电话
            String telephone = String.valueOf(list.get(12)).trim();
            veteranMember.setTelephone(telephone.isEmpty() ? null : telephone);

            // 入伍地点
            String enlistmentPlace = String.valueOf(list.get(13)).trim();
            veteranMember.setEnlistmentPlace(enlistmentPlace.isEmpty() ? null : enlistmentPlace);

            // 入伍日期
            String enlistmentDate = String.valueOf(list.get(14)).trim();
            // if (!enlistmentDate.isEmpty() && !isValidDate(enlistmentDate)) {
            //     throw new IllegalArgumentException("第 " + (i + 1) + " 行入伍日期格式错误");
            // }
            veteranMember.setEnlistmentDate(enlistmentDate.isEmpty() ? null : enlistmentDate);

            // 退伍日期
            String dischargeDate = String.valueOf(list.get(15)).trim();
            // if (!dischargeDate.isEmpty() && !isValidDate(dischargeDate)) {
            //     throw new IllegalArgumentException("第 " + (i + 1) + " 行退伍日期格式错误");
            // }
            veteranMember.setDischargeDate(dischargeDate.isEmpty() ? null : dischargeDate);

            // 兵种
            String armClass = String.valueOf(list.get(16)).trim();
            veteranMember.setArmClass(armClass.isEmpty() ? null : armClass);

            // 服役状态
            String isServingStr = String.valueOf(list.get(17)).trim();
            veteranMember.setIsServing("是".equals(isServingStr) ? 1 : 0);

            // // 立功情况
            // String hasMeritoriousStr = String.valueOf(list.get(18)).trim();
            // veteranMember.setHasMeritorious("是".equals(hasMeritoriousStr) ? 1 : 0);

            // 奖励
            String awards = String.valueOf(list.get(18)).trim();
            veteranMember.setAwards(awards.isEmpty() ? null : awards);

            // 备注
            String remark = String.valueOf(list.get(19)).trim();
            veteranMember.setRemark(remark.isEmpty() ? null : remark);



            veteranMemberList.add(veteranMember);
        }

        // 将Excel中的数据插入数据库
        int i = veteranMemberMapper.insertVeteranMember(veteranMemberList);
        if (i != 0) {
            System.out.println("数据插入成功！！！");
        }else {
            return "文档内无数据，请重新导入";
        }


        return "数据插入成功";
    }
}
